package com.fuchuang.seckillsystem.controller;

import com.fuchuang.seckillsystem.dto.OrderInfo;
import com.fuchuang.seckillsystem.dto.OrderQuery;
import com.fuchuang.seckillsystem.entity.MyUserDetails;
import com.fuchuang.seckillsystem.service.IOrderService;
import com.fuchuang.seckillsystem.vo.RespBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("order")
public class OrderController {
    
    
    @Autowired
    private IOrderService orderService;
    
    @GetMapping("orderDetail")
    public RespBean orderDetail(Integer orderId) {
        OrderInfo orderInfo = orderService.getOrderDetail(orderId);
        return RespBean.success(orderInfo);
    }
    
    @PostMapping("userOrderList")
    public RespBean orderInfoList(@RequestBody OrderQuery orderQuery, @AuthenticationPrincipal MyUserDetails userDetails) {
        orderQuery.setUserId(userDetails.getId());
        Map<String, Object> userOrderInfo = orderService.getUserOrderInfo(orderQuery);
        return RespBean.success(userOrderInfo);
    }
    
    @GetMapping("pay")
    public RespBean pay(Integer orderId, Integer userId, @AuthenticationPrincipal MyUserDetails userDetails) {
        //实际支付时，无需上传userId
        if (userId == null) {
            userId = userDetails.getId();
        }
        orderService.pay(orderId, userId);
        return RespBean.success();
    }
    
    @GetMapping("cancel")
    public RespBean cancel(Integer orderId, @AuthenticationPrincipal MyUserDetails userDetails) {
        orderService.cancelOrder(orderId, userDetails.getId());
        return RespBean.success();
    }
    
    @PostMapping("allOrder")
    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_FORM')")
    public RespBean allOrderInfo(@RequestBody OrderQuery orderQuery) {
        Map<String, Object> allOrderInfo = orderService.getAllOrderInfo(orderQuery);
        return RespBean.success(allOrderInfo);
    }
    
    
}
